#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Time       :   11:17
# Author     : Y4
# Site       : 返回值 手机验证 | 数据加密
# File       : util.py

# 短信验证
import base64
import hashlib
import time
import uuid

import requests
from flask import jsonify
from sqlalchemy.orm import class_mapper
from App.settings import UPLOAD_DIR, FILE_PATH, ALLOWED_EXTENSIONS


# sql 序列化
def multi_dict(result):
    from collections import Iterable
    # 转换完成后，删除  '_sa_instance_state' 特殊属性
    try:
        if isinstance(result, Iterable):
            tmp = [dict(zip(res.__dict__.keys(), res.__dict__.values())) for res in result]
            for t in tmp:
                t.pop('_sa_instance_state')
        else:
            tmp = dict(zip(result.__dict__.keys(), result.__dict__.values()))
            tmp.pop('_sa_instance_state')
        return tmp
    except BaseException as e:
        print(e.args)
        raise TypeError('Type error of parameter')

def single_dict(model, *args, **kwargs):
    columns = [c.key for c in class_mapper(model.__class__).columns]
    _dict = dict((c, getattr(model, c)) for c in columns)
    new_dict = {}

    if not args:
        return _dict

    for arg in args:
        if arg == 'all':
            return _dict
        new_dict[arg] = _dict.pop(arg)
    return new_dict


# 返回值
def rerep(msg='ok', status=200, data=None):
    data = {
        "msg": msg,
        "status": status,
        "data": data
    }
    return jsonify(data)


# 短信验证
def send_phone_code(phone):
    url = 'https://api.netease.im/sms/sendcode.action'
    nonce = hashlib.new("sha512", str(time.time()).encode("utf-8")).hexdigest()
    curtime = str(int(time.time()))

    sha1 = hashlib.sha1()
    secret = '95f79055cf0f'
    sha1.update((secret + nonce + curtime).encode("utf-8"))

    check_sum = sha1.hexdigest()
    headers = {
        "AppKey": "3772e868b6f7de02eb25a0c1b1ed6800",
        "Nonce": nonce,
        "CurTime": curtime,
        "CheckSum": check_sum
    }
    post_data = {
        "mobile": phone
    }
    res = requests.post(url, data=post_data, headers=headers)
    return res


# 数据加密
def make_data_secret(data):
    encode_content = base64.standard_b64encode(data.encode("utf-8")).decode("utf-8")
    add_content_encode_content = "kene" + encode_content + "kene"
    encode_content_twice = base64.standard_b64encode(add_content_encode_content.encode("utf-8")).decode("utf-8")
    return encode_content_twice


# 图片修改名称
def filename_transfer(filename):
    ext_name = filename.rsplit('.', 1)[1]
    new_filename = uuid.uuid4().hex + '.' + ext_name
    # 图片保存本地的路径
    save_path = UPLOAD_DIR + new_filename
    # 图片保存在数据库的路径
    upload_path = FILE_PATH + new_filename
    return save_path, upload_path


# 检查图片上传的格式
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
